package com.dng.book.controller;

import com.dng.book.entity.User;
import com.dng.book.service.UserService;
import com.dng.book.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import cn.hutool.crypto.digest.DigestUtil;
import com.dng.book.dto.UploadAvatarRequest;

/**
 * 测试控制器
 * 
 * @author dng
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private RedisUtil redisUtil;
    
    @Resource
    private UserService userService;

    /**
     * 测试Redis连接
     */
    @GetMapping("/redis")
    public Map<String, Object> testRedis() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 测试Redis连接
            boolean connectionTest = redisUtil.testConnection();
            result.put("connectionTest", connectionTest);
            
            // 测试设置和获取
            String testKey = "test_key_" + System.currentTimeMillis();
            String testValue = "test_value_" + System.currentTimeMillis();
            
            boolean setResult = redisUtil.set(testKey, testValue, 60, java.util.concurrent.TimeUnit.SECONDS);
            String getValue = redisUtil.get(testKey);
            
            result.put("setResult", setResult);
            result.put("getValue", getValue);
            result.put("expectedValue", testValue);
            result.put("valueMatch", testValue.equals(getValue));
            
            // 清理测试数据
            redisUtil.delete(testKey);
            
            log.info("Redis测试结果: {}", result);
            
        } catch (Exception e) {
            log.error("Redis测试失败", e);
            result.put("error", e.getMessage());
        }
        
        return result;
    }

    /**
     * 测试验证码相关Redis操作
     */
    @GetMapping("/captcha")
    public Map<String, Object> testCaptcha(@RequestParam String username) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 设置验证码
            String captchaKey = "captcha:" + username;
            String captchaValue = "1234";
            
            boolean setResult = redisUtil.set(captchaKey, captchaValue, 5, java.util.concurrent.TimeUnit.MINUTES);
            result.put("setResult", setResult);
            
            // 立即获取验证码
            String getValue = redisUtil.get(captchaKey);
            result.put("getValue", getValue);
            result.put("expectedValue", captchaValue);
            result.put("valueMatch", captchaValue.equals(getValue));
            
            // 检查所有captcha相关key
            java.util.Set<String> keys = redisUtil.keys("captcha:*");
            result.put("captchaKeys", keys);
            
            // 检查key是否存在
            boolean hasKey = redisUtil.hasKey(captchaKey);
            result.put("hasKey", hasKey);
            
            // 获取过期时间
            long expire = redisUtil.getExpire(captchaKey);
            result.put("expire", expire);
            
            log.info("验证码测试结果: {}", result);
            
        } catch (Exception e) {
            log.error("验证码测试失败", e);
            result.put("error", e.getMessage());
        }
        
        return result;
    }

    /**
     * 测试手机号查询
     */
    @GetMapping("/test/phone")
    public Map<String, Object> testPhone(@RequestParam String phone) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean exists = userService.existsByPhone(phone);
            User user = userService.getByPhone(phone);
            
            result.put("phone", phone);
            result.put("exists", exists);
            result.put("user", user != null ? user.getUsername() : null);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        return result;
    }

    /**
     * 测试密码哈希
     */
    @GetMapping("/test/password")
    public Map<String, Object> testPassword(@RequestParam String password) {
        String encryptedPassword = DigestUtil.md5Hex(password);
        Map<String, Object> result = new HashMap<>();
        result.put("originalPassword", password);
        result.put("encryptedPassword", encryptedPassword);
        result.put("length", encryptedPassword.length());
        return result;
    }
    
    @GetMapping("/test/avatar")
    public Map<String, Object> testAvatar(@RequestParam String username) {
        Map<String, Object> result = new HashMap<>();
        try {
            String avatar = userService.getAvatar(username);
            result.put("username", username);
            result.put("avatar", avatar);
            result.put("hasAvatar", avatar != null && !avatar.isEmpty());
            return result;
        } catch (Exception e) {
            result.put("error", e.getMessage());
            return result;
        }
    }
    
    @PostMapping("/test/uploadAvatar")
    public Map<String, Object> testUploadAvatar(@RequestBody UploadAvatarRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String avatarUrl = "data:" + request.getFileType() + ";base64," + request.getAvatarData();
            
            // 记录数据长度
            int dataLength = request.getAvatarData().length();
            int fullUrlLength = avatarUrl.length();
            
            result.put("username", request.getUsername());
            result.put("dataLength", dataLength);
            result.put("fullUrlLength", fullUrlLength);
            result.put("fileType", request.getFileType());
            
            boolean success = userService.uploadAvatar(request.getUsername(), avatarUrl);
            result.put("success", success);
            result.put("avatarUrl", avatarUrl);
            return result;
        } catch (Exception e) {
            result.put("error", e.getMessage());
            result.put("errorType", e.getClass().getSimpleName());
            return result;
        }
    }
} 